package com.simou.controller;

import com.simou.pojo.User;
import com.simou.service.ProviderServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.simou.pojo.Provider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;

/*  处理用户相关请求，分为三个模块
    1. 路径转发
    2. AJAX请求
    3. 表单请求
*/

@Controller
public class ProviderController {

    @Autowired
    ProviderServiceImpl providerService;

/*  *****************************************************
    1. 路径转发
    *****************************************************
*/

    @RequestMapping("jsp/provider.do")
    public String selectMethod(String method) {
        System.out.println("method:" + method);
        switch (method) {
            case "query":
                return "forward:getProviderList";
            case "add":
                return "forward:addProvider";
            case "modify":
                return "forward:modify.do";
            case "modifyexe":
                return "forward:modifyProvider";
            case "pwdmodify":
                return "forward:verifyOldPassword";
            case "savepwd":
                return "forward:savepwd";
            case "view":
                return "forward:view";
            case "delprovider":
                return "forward:delprovider";
            default:
                return "/";
        }
    }

/*  *****************************************************
    2. AJAX请求
    *****************************************************
*/

//  2.1 根据uid填充被修改供应商的原信息
    @RequestMapping("jsp/modify.do")
    public String modifyProvider(String method,Integer proid,Model model,HttpSession session){
        System.out.println("method:"+method);
        System.out.println("proid:"+proid);
        System.out.println("modifyexe uid:"+proid);
        Object obj = session.getAttribute("providerList");
        if(obj!=null){
            List<Provider> providerList = (List<Provider>) obj;
            for (Provider provider : providerList) {
                if (provider.getId()==proid){
                    // 将用户信息发送给前端，前端自动填充用户的原数据
                    model.addAttribute("provider",provider);
                }
            }
        }
        return "providermodify";
//等同于 return "forward:/WEB-INF/jsp/providermodify.jsp";
//等同于 return "/providermodify";
}

    //  2.2 删除用户
    @RequestMapping("/jsp/delprovider")
    @ResponseBody
    public String deleteProvider(String method,long proid) throws JsonProcessingException {
        System.out.println("删除用户 method："+method);
        System.out.println("删除用户 proid："+proid);
        int i = providerService.deleteProvider(proid);
        HashMap<String, String> resultMap = new HashMap<>();
        resultMap.put("delResult",i>0?"true":"false");
        System.out.println(i>0?"删除成功":"删除失败");
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(resultMap);
    }

/*  *****************************************************
    3. 表单请求
    *****************************************************
*/

    //  3.1 查询用户信息
    @RequestMapping("jsp/getProviderList")
    public String getProviderList(Model model, String pageIndex, String queryProCode, String queryProName, HttpSession session){
        System.out.println(queryProCode);
        System.out.println(queryProName);
        int pageSize = 5;
        int currentPageNo = 1;
        long providerRole = 0l;
        if(StringUtils.hasLength(pageIndex)){
            currentPageNo = Integer.parseInt(pageIndex);
        }
        // 1.查询数据库中一共有多少个用户
        int totalCount = providerService.getProvidersCount(queryProCode,queryProName);

        // 2.查询用户信息（根据limit和检索条件）
        // 起始 = (currentPageNo-1)*5      currentPageNo=1: limit 0,5 ;currentPageNo=2: limit 5,5
        List<Provider> providerList = providerService.getProvidersByLimit((currentPageNo - 1) * 5, pageSize,queryProCode, queryProName);
        // 根据总用户数算出总页数(向上取整)
        int totalPageCount = (int)Math.ceil(new BigDecimal(totalCount).divide(new BigDecimal(pageSize)).doubleValue());

        System.out.println("queryProName:" + queryProName);
        System.out.println("queryProCode:" + queryProCode);
        System.out.println("pageIndex:" + pageIndex);
        System.out.println("供应商名称：" + queryProName);
        System.out.println("供应商编码：" + queryProCode);
        System.out.println("totalPageCount --> " + totalPageCount);
        System.out.println("totalCount --> " + totalCount);
        System.out.println("pageSize --> " + pageSize);
        System.out.println("currentPageNo --> " + currentPageNo);
        System.out.println("providerList --> " + providerList);

        model.addAttribute("queryProCode",queryProCode);
        model.addAttribute("queryProName",queryProName);
        model.addAttribute("queryProviderRole",providerRole);
        model.addAttribute("totalPageCount",totalPageCount);
        model.addAttribute("totalCount",totalCount);
        model.addAttribute("pageSize",pageSize);
        model.addAttribute("currentPageNo",currentPageNo);
        model.addAttribute("providerList",providerList);

        // 将用户列表存储到session中，方便后续使用
        session.setAttribute("providerList",providerList);
        return "providerlist";
    }

//  3.2 修改用户信息
    @RequestMapping("/jsp/modifyProvider")
    public String modifyProvider(long proid,Provider provider,HttpSession session){
        System.out.println("修改页面---[proid]:"+proid);
        Object obj = session.getAttribute("userSession");
        System.out.println("obj的值为"+obj);
        if(obj!=null){
            // 当前登录用户
            User currentUser = (User) obj;
            provider.setModifyBy(currentUser.getId());
        }
        provider.setModifyDate(new Timestamp(System.currentTimeMillis()));
        // provider里面存放修改的信息
        System.out.println("修改用户---[provider]:"+provider);
        int i = providerService.updateProvider(proid, provider);
        System.out.println(i>0?"修改成功":"修改失败");
        return "forward:getProviderList";
    }

    //  3.3 添加用户
    @RequestMapping("/jsp/addProvider")
    public String addProvider(Provider provider,HttpSession session){
        Object obj = session.getAttribute("userSession");
        if(obj!=null){
            User currentUser = (User) obj;
            provider.setCreatedBy(currentUser.getId());
            provider.setCreationDate(new Timestamp(System.currentTimeMillis()));
        }
        System.out.println("addProvider 路径的provider:"+provider);
        int i = providerService.addProvider(provider);
        System.out.println(i>0?"添加成功":"添加失败");
        return "forward:getProviderList";
    }

    //  3.4 查看用户信息
    @RequestMapping("/jsp/view")
    public String viewProvider(String method,Integer proid,Model model,HttpSession session){
        System.out.println("method:"+method);
        System.out.println("proid:"+proid);
        // 取出查询用户列表时保存在session的providerList,以获取该用户信息
        Object obj = session.getAttribute("providerList");
        if (obj!=null){
            List<Provider> providerList = (List<Provider>) obj;
            for (Provider provider : providerList) {
                // 若uid相同，说明查询到用户信息
                if(provider.getId()==proid){
                    model.addAttribute("provider",provider);
                }
            }
        }
        return "providerview";
    }
}